import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import ChromeOptions
import undetected_chromedriver as uc
import zipfile
import time

def get_proxy():
    url = "https://dps.kdlapi.com/api/getdps/?secret_id=ondbxg8msovv7ury9qbe&signature=zft63syjut8u3og5m9j5wung50mwah5f&num=1&format=text&sep=1"
    proxy_address = requests.get(url)
    return proxy_address.text


proxy_address = get_proxy()
print(f"===============使用代理:{proxy_address}")
proxy_host = proxy_address.split(":")[0]            # proxy ip
proxy_port = proxy_address.split(":")[1]            # proxy port
# 代理信息
username = 'd2231274096'
password = 'ela9v3e9'

# Manifest V3 配置
manifest_json = """
{
    "version": "1.0.0",
    "manifest_version": 3,
    "name": "Chrome Proxy",
    "background": {
        "service_worker": "background.js"
    },
    "permissions": [
        "proxy",
        "webRequest",
        "webRequestAuthProvider"
    ],
    "host_permissions": [
        "<all_urls>"
    ]
}
"""

background_js = """
const config = {
    mode: "fixed_servers",
    rules: {
        singleProxy: {
            scheme: "http",
            host: "%s",
            port: %s
        },
        bypassList: ["localhost"]
    }
};

chrome.proxy.settings.set({value: config, scope: 'regular'}, function() {});

function callbackFn(details) {
    return {
        authCredentials: {
            username: "%s",
            password: "%s"
        }
    };
}

chrome.webRequest.onAuthRequired.addListener(
    callbackFn,
    {urls: ["<all_urls>"]},
    ['blocking']
);
""" % (proxy_host, proxy_port, username, password)

# 创建临时插件文件
plugin_file = 'proxy_auth_plugin.zip'
with zipfile.ZipFile(plugin_file, 'w') as zp:
    zp.writestr("manifest.json", manifest_json)
    zp.writestr("background.js", background_js)

# 配置Chrome选项
chrome_options = Options()
chrome_options.add_extension(plugin_file)

# # 可选：添加其他配置以避免被检测
# chrome_options.add_argument("--disable-blink-features=AutomationControlled")
# chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])

try:
    driver_path = r'C:\Program Files\Google\Chrome\Application\chromedriver.exe'
    print(11111)
    driver = uc.Chrome(driver_executable_path=driver_path,options=chrome_options)
    print(22222)
    driver.get("https://icanhazip.com/")
    time.sleep(10)
    print("页面IP:", driver.find_element_by_tag_name("body").text)
    # 等待一下，确保页面加载完成
    driver.implicitly_wait(5)
except Exception as e:
    print("启动失败:", e)
finally:
    # driver.quit()
    pass
